#!/usr/bin/env node

const Koa = require('koa'),
      app = new Koa(),
      bodyparser = require('koa-bodyparser'),
      user = require('./routes/user.js'),
      tasks = require('./routes/tasks.js'),
      json  = require('koa-json'),
      logger = require('koa-logger'),
      {JWT_KEY} = require('./lib/constant.js'),
      jwt    = require('koa-jwt'),
      jwt2   = require('jsonwebtoken'),
      log = console.log;

app.use(json());
app.use(logger());
app.use(jwt({ secret:JWT_KEY }).unless({path:/\/api\/users\/login$/}));

app.use(bodyparser({ enableTypes: ['json','form','text'] }));
app.use(async(ctx,next) => {   
  //get token
  let token = ctx.header.authorization;
  if(typeof token !== 'undefined'){
    token = token.split(' ')[1];
    // parse token get user id
    let user = jwt2.verify(token,JWT_KEY);
    console.log(user);
    ctx.userId = user.id;
  }
  
  
  await next();
})
app.use(tasks.routes());
app.use(user.routes());

app.listen(8080);
